'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';

interface InventoryHistory {
  id: number;
  type: 'in' | 'out' | 'adjust' | 'initial';
  quantity: number;
  previousQuantity: number | null;
  newQuantity: number | null;
  notes: string | null;
  createdBy: string;
  createdAt: string;
  productName: string;
  productSku: string;
}

export default function InventoryHistoryPage() {
  const [history, setHistory] = useState<InventoryHistory[]>([]);
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState({
    productId: '',
    type: '',
    startDate: '',
    endDate: '',
  });

  useEffect(() => {
    fetchHistory();
  }, []);

  const fetchHistory = async (filterParams = {}) => {
    try {
      const params = new URLSearchParams({ ...filters, ...filterParams });
      const response = await fetch(`/api/inventory/history?${params}`);
      
      if (response.ok) {
        const data = await response.json();
        setHistory(Array.isArray(data) ? data : []);
      } else {
        console.error('获取库存记录失败:', await response.json());
        setHistory([]);
      }
    } catch (error) {
      console.error('获取库存记录失败:', error);
      setHistory([]);
    } finally {
      setLoading(false);
    }
  };

  const getTypeText = (type: string) => {
    const typeMap = {
      'in': '入库',
      'out': '出库',
      'adjust': '调整',
      'initial': '初始'
    };
    return typeMap[type as keyof typeof typeMap] || type;
  };

  const getTypeColor = (type: string) => {
    const colorMap = {
      'in': 'bg-green-100 text-green-800',
      'out': 'bg-red-100 text-red-800',
      'adjust': 'bg-blue-100 text-blue-800',
      'initial': 'bg-gray-100 text-gray-800'
    };
    return colorMap[type as keyof typeof colorMap] || 'bg-gray-100 text-gray-800';
  };

  const getTypeIcon = (type: string) => {
    const iconMap = {
      'in': '⬆️',
      'out': '⬇️',
      'adjust': '↔️',
      'initial': '📦'
    };
    return iconMap[type as keyof typeof iconMap] || '';
  };

  const handleFilterChange = (key: string, value: string) => {
    setFilters(prev => ({ ...prev, [key]: value }));
  };

  const handleApplyFilters = () => {
    setLoading(true);
    fetchHistory(filters);
  };

  const handleClearFilters = () => {
    setFilters({ productId: '', type: '', startDate: '', endDate: '' });
    setLoading(true);
    fetchHistory({});
  };

  if (loading) return <div className="p-8">加载中...</div>;

  return (
    <div className="p-8">
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <Link href="/inventory" className="text-gray-600 hover:text-gray-900">
            ← 返回库存管理
          </Link>
          <h1 className="text-3xl font-bold">库存记录</h1>
        </div>
        <button className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
          导出记录
        </button>
      </div>

      {/* 筛选面板 */}
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 className="text-lg font-semibold mb-4">筛选条件</h3>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">操作类型</label>
            <select
              value={filters.type}
              onChange={(e) => handleFilterChange('type', e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md"
            >
              <option value="">所有类型</option>
              <option value="in">入库</option>
              <option value="out">出库</option>
              <option value="adjust">调整</option>
              <option value="initial">初始</option>
            </select>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">开始日期</label>
            <input
              type="date"
              value={filters.startDate}
              onChange={(e) => handleFilterChange('startDate', e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md"
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">结束日期</label>
            <input
              type="date"
              value={filters.endDate}
              onChange={(e) => handleFilterChange('endDate', e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-md"
            />
          </div>
          
          <div className="flex items-end">
            <button
              onClick={handleApplyFilters}
              className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 mr-2"
            >
              应用筛选
            </button>
            <button
              onClick={handleClearFilters}
              className="px-4 py-2 text-gray-700 border border-gray-300 rounded-md hover:bg-gray-50"
            >
              清除
            </button>
          </div>
        </div>
      </div>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-gray-800">{history.length}</div>
          <div className="text-sm text-gray-600">总记录数</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-green-600">
            {history.filter(h => h.type === 'in').length}
          </div>
          <div className="text-sm text-gray-600">入库记录</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-red-600">
            {history.filter(h => h.type === 'out').length}
          </div>
          <div className="text-sm text-gray-600">出库记录</div>
        </div>
        <div className="bg-white rounded-lg shadow p-4 text-center">
          <div className="text-2xl font-bold text-blue-600">
            {history.filter(h => h.type === 'adjust').length}
          </div>
          <div className="text-sm text-gray-600">调整记录</div>
        </div>
      </div>

      {/* 库存记录表格 */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                产品
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作类型
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                数量变化
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                库存变化
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                备注
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作人
              </th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作时间
              </th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {history.map((record) => (
              <tr key={record.id}>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div>
                    <div className="text-sm font-medium text-gray-900">{record.productName}</div>
                    <div className="text-sm text-gray-500">{record.productSku}</div>
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getTypeColor(record.type)}`}>
                    {getTypeIcon(record.type)} {getTypeText(record.type)}
                  </span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="text-sm text-gray-900">
                    {record.type === 'in' ? '+' : record.type === 'out' ? '-' : '±'}{record.quantity}
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  {record.previousQuantity !== null && record.newQuantity !== null && (
                    <div className="text-sm text-gray-900">
                      {record.previousQuantity} → {record.newQuantity}
                    </div>
                  )}
                </td>
                <td className="px-6 py-4">
                  <div className="text-sm text-gray-900 max-w-xs truncate">
                    {record.notes}
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {record.createdBy}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {new Date(record.createdAt).toLocaleString('zh-CN')}
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        {history.length === 0 && (
          <div className="text-center py-12">
            <div className="text-gray-400 text-lg">暂无库存记录</div>
            <p className="text-gray-500 text-sm mt-2">开始进行库存操作后，记录将显示在这里</p>
          </div>
        )}
      </div>

      <div className="mt-6 flex justify-between items-center">
        <div className="text-sm text-gray-600">
          显示 {history.length} 条记录
        </div>
        <div className="flex space-x-2">
          <button className="px-3 py-1 border border-gray-300 rounded-md text-sm">
            上一页
          </button>
          <button className="px-3 py-1 border border-gray-300 rounded-md text-sm bg-blue-600 text-white">
            1
          </button>
          <button className="px-3 py-1 border border-gray-300 rounded-md text-sm">
            下一页
          </button>
        </div>
      </div>
    </div>
  );
}